Binary Tree Maximum Path Sum
Question
Given a binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
For example:
Given the below binary tree,
|
|
Return 6
.
Analysis
如上述题解所说的,最后的路径可能有四种情况:
- 只有node
- node+leftsub
- node+rightsub
- node+leftsub+rightsub
故在计算的过程中,假如left/right=0,则可得1-3种情况的值,若均不为0,则为第4种情况,同时与已经记录的maxvalue进行大小比较确定师傅需要更新。
由于路径不能回退的特性,所以返回值是right,left的最大值加上当前的val
Code
|
|
Binary Tree Postorder Traversal
Question
Given a binary tree, return the postorder traversal of its nodes’ values.
For example:
Given binary tree {1,#,2,3}
,
|
|
return [3,2,1]
.
Analysis
正常的递归后续遍历
Code
|
|